<?php

namespace App\Http\Controllers;

use App\Models\FilesModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImageController extends Controller
{
    public function uploadImages(Request $request)
    {
        // 验证请求参数
//        $request->validate([
//            'main_image' => 'required|image|mimes:jpeg,png,jpg',
//            'additional_images' => 'required|array',
//            'additional_images.*' => 'image|mimes:jpeg,png,jpg'
//        ]);

        $mainImage = $request->file('main_image');
        $additionalImages = $request->file('additional_images');

        // 保存主图到 public/storage/images/main
        $name = $mainImage->getClientOriginalName();
        $type = pathinfo($name, PATHINFO_EXTENSION);
        $extension = $mainImage->getClientOriginalExtension();
        $size = $mainImage->getSize();
        $filename = date('YmdHis') . uniqid() . '.' . $extension;
        $path = $mainImage->storeAs('images/main', $filename);
        $fileable_type = '千图成像主图';
        $url = Storage::url($path);
        $main_url = $url;

            // 创建文件记录
        $file = FilesModel::create(compact('type', 'path', 'url', 'name', 'size', 'fileable_type'));

        // 保存辅助图片到 public/storage/images/other
        $additionalImagesPaths = [];
        foreach ($additionalImages as $image) {
            $name = $image->getClientOriginalName();
            $type = pathinfo($name, PATHINFO_EXTENSION);
            $extension = $image->getClientOriginalExtension();
            $size = $image->getSize();
            $filename = date('YmdHis') . uniqid() . '.' . $extension;
            $path = $image->storeAs('images/other', $filename);
            $fileable_type = '千图成像附图';
            $url = Storage::url($path);
            $additionalImagesPaths[] = $url;
            // 创建文件记录
            $file = FilesModel::create(compact('type', 'path', 'url', 'name', 'size', 'fileable_type'));
        }

        // 处理图片
        $combinedImagePath = $this->processImages($main_url, $additionalImagesPaths);

        // 返回处理后的图片路径
        return response()->json(['combined_image_path' => Storage::url($combinedImagePath)]);
    }

    private function processImages($mainImagePath, $additionalImagesPaths)
    {
        // 加载主图
        $mainImage = $this->loadImage($mainImagePath);
        if (!$mainImage) {
            throw new \Exception("加载主图失败");
        }

        $width = imagesx($mainImage);
        $height = imagesy($mainImage);

        // 创建一个新的图像用于组合
        $combinedImage = imagecreatetruecolor($width, $height);

        // 遍历主图的每个像素
        for ($y = 0; $y < $height; $y++) {
            for ($x = 0; $x < $width; $x++) {
                $mainPixelColor = imagecolorat($mainImage, $x, $y);
                $closestColor = $this->findClosestColor($mainPixelColor, $additionalImagesPaths, $mainImage);

                // 设置组合图的像素
                imagesetpixel($combinedImage, $x, $y, $closestColor);
            }
        }

        // 保存组合图
        $combinedImagePath = 'images/' . uniqid() . '.jpg';
        if (!imagejpeg($combinedImage, storage_path('app/' . $combinedImagePath))) {
            throw new \Exception("保存组合图失败");
        }

        // 释放图像资源
        imagedestroy($mainImage);
        imagedestroy($combinedImage);

        return $combinedImagePath;
    }

    private function loadImage($path)
    {
        $new_path = str_replace('/', '\\', ltrim($path, '/'));
        $filePath = public_path($new_path);
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);


        if (!file_exists($filePath)) {
            echo "文件不存在----: " . $filePath;
            return null;
        }

        switch ($extension) {
            case 'jpeg':
            case 'jpg':
                return imagecreatefromjpeg($filePath);
            case 'png':
                return imagecreatefrompng($filePath);
            default:
                return null;
        }
    }

    private function findClosestColor($mainPixelColor, $additionalImagesPaths, $mainImage)
    {
        $closestColor = null;
        $minDistance = PHP_INT_MAX;

        foreach ($additionalImagesPaths as $url) {
            $path = str_replace('/storage/', '', $url);
            $image = $this->loadImage($path);
            dd($image);
            if (!$image) {
                continue;
            }

            $additionalWidth = imagesx($image);
            $additionalHeight = imagesy($image);

            for ($y = 0; $y < $additionalHeight; $y++) {
                for ($x = 0; $x < $additionalWidth; $x++) {
                    $additionalPixelColor = imagecolorat($image, $x, $y);
                    $distance = $this->colorDistance($mainPixelColor, $additionalPixelColor);

                    if ($distance < $minDistance) {
                        $minDistance = $distance;
                        $closestColor = $additionalPixelColor;
                    }
                }
            }

            imagedestroy($image);
        }

        // 如果没有找到合适的颜色，使用主图的像素颜色
        if ($closestColor === null) {
            $closestColor = $mainPixelColor;
        }

        return $closestColor;
    }

    private function colorDistance($color1, $color2)
    {
        $r1 = ($color1 >> 16) & 0xFF;
        $g1 = ($color1 >> 8) & 0xFF;
        $b1 = $color1 & 0xFF;

        $r2 = ($color2 >> 16) & 0xFF;
        $g2 = ($color2 >> 8) & 0xFF;
        $b2 = $color2 & 0xFF;

        return sqrt(pow($r2 - $r1, 2) + pow($g2 - $g1, 2) + pow($b2 - $b1, 2));
    }
}
